package com.specialtreasure.freightdepot.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.core.activity.BaseNewActivity;
import com.app.core.util.Base64;
import com.app.core.util.ImageUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.FullyGridLayoutManager;
import com.specialtreasure.freightdepot.adapter.GoodsListAdapter;
import com.specialtreasure.freightdepot.adapter.GridImageAdapter;
import com.specialtreasure.freightdepot.model.GoodsList;
import com.yanzhenjie.nohttp.Logger;


import java.util.ArrayList;
import java.util.List;

/**
 * 货物详情页
 */

public class GoodsDetailsActivity extends BaseNewActivity implements View.OnClickListener {

    public static final String TAG = "GoodsDetailsActivity";
    private ImageView iv_back;
    private TextView tv_title;
    private EditText et_goods_details;
    private EditText et_discharge_details;
    private EditText et_collection_money;
    private ListView lv_goods;

    private GoodsListAdapter goodsListAdapter;
    private List<GoodsList> goodsList = new ArrayList<>();
    private TextView tv_sure;
    private RadioButton rb_yes;
    private RadioButton rb_no;
    private RadioGroup rgp_select;

    private long collectionStatue = 1;//代收货款 0否 1是
    String photo1;//照片1
    String photo2;//照片2
    String itemDetailArr;//货物清单: (json格式List(ItemDetailResp))
    String loadingAddress;//装货地址
    String unloadingAddress;//卸货地址
    String collectionMoneyStr;//代收款金额

    //相册
    private List<LocalMedia> selectList = new ArrayList<>();
    private RecyclerView rlv_photo;
    private GridImageAdapter adapter;
    private int maxSelectNum = 2;
    private int compressMode = PictureConfig.LUBAN_COMPRESS_MODE;
    private int themeId;
    private int aspect_ratio_x, aspect_ratio_y;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_goods_details);
        initView();
        setData();
    }


    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        et_goods_details = (EditText) findViewById(R.id.et_goods_details);
        et_discharge_details = (EditText) findViewById(R.id.et_discharge_details);
        et_collection_money = (EditText) findViewById(R.id.et_collection_money);
        lv_goods = (ListView) findViewById(R.id.lv_goods);
        rlv_photo = (RecyclerView) findViewById(R.id.rlv_photo);

        tv_sure = (TextView) findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(this);
        rb_yes = (RadioButton) findViewById(R.id.rb_yes);
        rb_yes.setOnClickListener(this);
        rb_no = (RadioButton) findViewById(R.id.rb_no);
        rb_no.setOnClickListener(this);
        rgp_select = (RadioGroup) findViewById(R.id.rgp_select);
        rgp_select.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sure://传递参数到发布页面
                parameter();
                break;
        }
    }


    private void setData() {
        show(iv_back);
        show(tv_sure);
        tv_title.setText("货物详细信息");
        tv_sure.setText("确定");

        //初始化listview数据
        goodsListAdapter = new GoodsListAdapter(this);
        goodsList.add(0, new GoodsList());
        goodsListAdapter.setGoodsList(goodsList);
        lv_goods.setAdapter(goodsListAdapter);

        //radiobutton选中的值
        rgp_select.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                //获取变更后的选中项的ID
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton) findViewById(radioButtonId);
                String text = rb.getText().toString();

//                Logger.e("请求成功：" + text);
                if (text.equals("是")) {
                    collectionStatue = 1;
                } else {
                    collectionStatue = 0;
                }

            }
        });


        //图片
        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        rlv_photo.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        rlv_photo.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(GoodsDetailsActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(GoodsDetailsActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(GoodsDetailsActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });


    }


    /**
     * 参数拼接
     */
    private void parameter() {
        Intent intent = new Intent();
        intent.putExtra("collectionStatue", collectionStatue);
        intent.putExtra("loadingAddress", et_goods_details.getText().toString().trim());
        intent.putExtra("unloadingAddress", et_discharge_details.getText().toString().trim());
        intent.putExtra("collectionMoneyStr", et_collection_money.getText().toString().trim());

        List<GoodsList> goodsLists = goodsListAdapter.getGoodsList();
        if (goodsLists != null && goodsLists.size() > 0) {
            itemDetailArr = JSON.toJSON(goodsLists).toString();
//            Logger.e(JSON.toJSON(goodsLists).toString());
        }
        intent.putExtra("itemDetailArr", itemDetailArr);
        intent.putExtra("photo1", photo1);
        intent.putExtra("photo2", photo2);
        setResult(RESULT_OK, intent);
        finish();
    }


    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(GoodsDetailsActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .compress(true)// 是否压缩
                    .compressMode(compressMode)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
//                    .enableCrop(false)// 是否裁剪
//                    .previewImage(false)// 是否可预览图片
//                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
//                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
//                    .circleDimmedLayer(false)// 是否圆形裁剪
//                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
//                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
//                    .openClickSound(false)// 是否开启点击声音
//                    .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                    .previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
//                    .cropCompressQuality(90)// 裁剪压缩质量 默认100
//                    .compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
//                    .compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
//                    .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                    .rotateEnabled() // 裁剪是否可旋转图片
//                    .scaleEnabled()// 裁剪是否可放大缩小图片
//                    .videoQuality()// 视频录制质量 0 or 1
//                    .videoSecond()//显示多少秒以内的视频or音频也可适用
//                    .recordVideoSecond()//录制视频秒数 默认60s
//                    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
//                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code


        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    List<LocalMedia> tempList=PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    selectList.addAll(tempList);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    Logger.e("onActivityResult:" + selectList.size());

                    if (selectList != null && selectList.size() > 0) {
                        if (selectList.size() == 1) {
                            photo1 = Base64.encodeBytes(ImageUtils.getBytes(selectList.get(0).getCompressPath()));
                        } else {
                            photo1 = Base64.encodeBytes(ImageUtils.getBytes(selectList.get(0).getCompressPath()));
                            photo2 = Base64.encodeBytes(ImageUtils.getBytes(selectList.get(1).getCompressPath()));
                        }
                    }

                    break;
            }
        }
    }


    private void submit() {
        // validate
//        String details = et_goods_details.getText().toString().trim();
//        if (TextUtils.isEmpty(details)) {
//            Toast.makeText(this, "请输入装货详细地址", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        String detail = et_discharge_details.getText().toString().trim();
//        if (TextUtils.isEmpty(detail)) {
//            Toast.makeText(this, "请输入卸货详细地址", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        String money = et_collection_money.getText().toString().trim();
//        if (TextUtils.isEmpty(money)) {
//            Toast.makeText(this, "金额不能为空", Toast.LENGTH_SHORT).show();
//            return;
//        }

        // TODO validate success, do something

    }


    @Override
    public String getActiviyName() {
        return TAG;
    }
}
